<template>
  <el-dialog
    title="企业微信"
    :visible.sync="dialogFormVisible"
    :before-close="handleClose"
    width="700px"
    custom-class="enterprise-dialog-box"
  >
    <el-form
      :model="configData"
      :rules="rules"
      ref="configData"
      label-width="150px"
      label-position="right"
      size="small"
      style="width: 98%"
    >
      <el-divider content-position="left" class="divider"
        >通讯录同步设置</el-divider
      >
      <el-form-item label="企业ID" prop="corpid">
        <el-input
          v-model="configData.corpid"
          placeholder="位于我的企业--企业ID"
        ></el-input>
      </el-form-item>
      <el-form-item label="URL">
        <el-input v-model="addressBookUrl" readonly class="w88"></el-input>
        <el-tooltip
          class="item"
          effect="dark"
          content="点击复制"
          :open-delay="300"
          :hide-after="2000"
          placement="left"
        >
          <el-button
            type="primary"
            plain
            v-on:click="copyStr('addUrl')"
            class="btnCopy addUrl"
            :data-clipboard-text="addressBookUrl"
            >复制</el-button
          >
        </el-tooltip>
      </el-form-item>
      <el-form-item label="Secret" prop="user">
        <el-input
          v-model="configData.user"
          placeholder="位于管理工具--通讯录同步"
        ></el-input>
      </el-form-item>
      <el-form-item label="Token" prop="token">
        <el-input
          v-model="configData.token"
          placeholder="位于管理工具--通讯录同步--服务器事件编辑"
          class="w88"
          readonly
        ></el-input>
        <el-tooltip
          class="item"
          effect="dark"
          content="点击复制"
          :open-delay="300"
          :hide-after="2000"
          placement="left"
        >
          <el-button
            type="primary"
            plain
            v-on:click="copyStr('addToken')"
            class="btnCopy addToken"
            :data-clipboard-text="configData.token"
            >复制</el-button
          >
        </el-tooltip>
      </el-form-item>
      <el-form-item label="EncodingAESKey" prop="encodingAESKey">
        <el-input
          v-model="configData.encodingAESKey"
          placeholder="位于管理工具--通讯录同步--服务器事件编辑"
          class="w88"
          readonly
        ></el-input>
        <el-tooltip
          class="item"
          effect="dark"
          content="点击复制"
          :open-delay="300"
          :hide-after="2000"
          placement="left"
        >
          <el-button
            type="primary"
            plain
            v-on:click="copyStr('addAESKey')"
            class="btnCopy addAESKey"
            :data-clipboard-text="configData.encodingAESKey"
            >复制</el-button
          >
        </el-tooltip>
      </el-form-item>
      <el-divider content-position="left" class="divider"
        >客户同步设置</el-divider
      >
      <el-form-item label="URL">
        <el-input v-model="customerUrl" readonly class="w88"></el-input>
        <el-tooltip
          class="item"
          effect="dark"
          content="点击复制"
          :open-delay="300"
          :hide-after="2000"
          placement="left"
        >
          <el-button
            type="primary"
            plain
            v-on:click="copyStr('customerUrl')"
            class="btnCopy customerUrl"
            :data-clipboard-text="customerUrl"
            >复制</el-button
          >
        </el-tooltip>
      </el-form-item>
      <el-form-item label="Secret" prop="externalcontact">
        <el-input
          v-model="configData.externalcontact"
          placeholder="位于客户联系"
        ></el-input>
      </el-form-item>
      <el-form-item label="Token" prop="token">
        <el-input
          v-model="configData.token"
          placeholder="位于客户联系--服务器事件编辑"
          class="w88"
          readonly
        ></el-input>
        <el-tooltip
          class="item"
          effect="dark"
          content="点击复制"
          :open-delay="300"
          :hide-after="2000"
          placement="left"
        >
          <el-button
            type="primary"
            plain
            v-on:click="copyStr('customerToken')"
            class="btnCopy customerToken"
            :data-clipboard-text="configData.token"
            >复制</el-button
          >
        </el-tooltip>
      </el-form-item>
      <el-form-item label="EncodingAESKey" prop="encodingAESKey">
        <el-input
          v-model="configData.encodingAESKey"
          placeholder="位于客户联系--服务器事件编辑"
          class="w88"
          readonly
        ></el-input>
        <el-tooltip
          class="item"
          effect="dark"
          content="点击复制"
          :open-delay="300"
          :hide-after="2000"
          placement="left"
        >
          <el-button
            type="primary"
            plain
            v-on:click="copyStr('customerAESKey')"
            class="btnCopy customerAESKey"
            :data-clipboard-text="configData.encodingAESKey"
            >复制</el-button
          >
        </el-tooltip>
      </el-form-item>
      <el-divider content-position="left" class="divider"
        >小程序设置</el-divider
      >
      <el-form-item label="新车集客Secret">
        <el-input
          v-model="configData.minisignup"
          placeholder="位于应用管理-应用-小程序"
        ></el-input>
      </el-form-item>
      <el-form-item label="元通汽车Secret">
        <el-input
          v-model="configData.yt_minisignup"
          placeholder="位于应用管理-应用-小程序"
        ></el-input>
      </el-form-item>
      <el-form-item label="元通汽车AgentID">
        <el-input
          v-model="configData.yt_minisignup_agent"
          placeholder="位于应用管理-应用-小程序"
        ></el-input>
      </el-form-item>
      <el-form-item label="售后团购Secret">
        <el-input
          v-model="configData.secret.groupBug"
          placeholder="位于应用管理-应用-小程序"
        ></el-input>
      </el-form-item>
      <el-form-item label="视频直连Secret">
        <el-input
          v-model="configData.secret.videoConnection"
          placeholder="位于应用管理-应用-小程序"
        ></el-input>
      </el-form-item>
      <el-form-item label="IM聊天Secret">
        <el-input
          v-model="configData.secret.IM"
          placeholder="位于应用管理-应用-小程序"
        ></el-input>
      </el-form-item>
      <el-divider content-position="left" class="divider"
        >自建应用设置</el-divider
      >
      <el-form-item label="AgentID">
        <el-input v-model="configData.secret.sop_AgentId"></el-input>
      </el-form-item>
      <el-form-item label="Secret">
        <el-input v-model="configData.secret.sop_secret"></el-input>
      </el-form-item>
      <el-form-item position="right">
        <!-- <el-button @click="resetForm('addressBookConfig')">重置</el-button> -->
        <el-tooltip
          class="item"
          effect="dark"
          content="随机生成Token和EncodingAESKey"
          placement="right"
          :open-delay="300"
          :hide-after="3000">
          <el-button type="danger" @click.prevent="getJsTokenAdnAES()">随机生成</el-button>
        </el-tooltip>
        <el-button type="success" @click="submitForm('configData')" class="btnSave">保存</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import Clipboard from "clipboard";
export default {
  name: "enterpriseConfig",
  data() {
    return {
      dialogFormVisible: false,
      storeId: 0,
      addressBookUrl: "",
      customerUrl: "",
      configData: {
        corpid: "",
        user: "",
        externalcontact: "",
        token: "",
        encodingAESKey: "",
        minisignup: "",
        yt_minisignup: "",
        yt_minisignup_agent: "",
        secret: {}
      },
      rules: {
        corpid: [{ required: true, message: "请输入企业ID", trigger: "blur" }],
        user: [{ required: true, message: "请输入Secret", trigger: "blur" }],
        externalcontact: [
          { required: true, message: "请输入Secret", trigger: "blur" },
        ],
        token: [
          {
            required: true,
            message: "请生成Token",
            trigger: "blur",
          },
        ],
        encodingAESKey: [
          {
            required: true,
            message: "请生成EncodingAESKey",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    init(data) {
      //初始化
      if (data < 0) {
        this.$message.error("店铺不存在");
        return;
      }
      this.storeId = data;
      this.addressBookUrl =
        "https://api.mycjj.com/b/weixin/index.php?act=user&op=callbackForUser&store_id=" +
        this.storeId;
      this.customerUrl =
        "https://api.mycjj.com/b/weixin/index.php?act=externalContact&op=callbackForExternalContact&store_id=" +
        this.storeId;
      // console.log(data);
      this.dialogFormVisible = true;

      //获取店铺企业微信配置
      this.$http
        .get(
          "/admin/store/index.php?act=enterpriseInfo&op=enterpriseList&store_id=" +
            this.storeId
        )
        .then((res) => {
          if (res.code == 1) {console.log(res)
            console.log(res.data);
            if (res.data.list != null) {
              var config = res.data.list[0];
              console.log(res.data.list);
              this.configData.corpid = config.corpid; //企业ID
              this.configData.user = config.user; //通讯录Secret
              this.configData.token = config.token; //通讯录Token
              this.configData.encodingAESKey = config.encodingAesKey; //通讯录encodingAesKey
              this.configData.externalcontact = config.externalcontact; //客户联系Secret
              this.configData.minisignup = config.minisignup; //新车集客小程序Secret
              this.configData.yt_minisignup = config.yt_minisignup; //元通汽车小程序Secret
              this.configData.yt_minisignup_agent = config.yt_minisignup_agent; //元通汽车小程序AgentID
              this.configData.secret = !config.secret ? {} : config.secret; 
            }
          }
        });
    },
    submitForm(formName) {
      //提交配置数据
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$http
            .post(
              "/admin/store/index.php?act=enterpriseInfo&op=setEnterprise",
              {
                store_id: this.storeId,
                externalcontact: this.configData.externalcontact,
                corpid: this.configData.corpid,
                user: this.configData.user,
                token: this.configData.token,
                encodingAesKey: this.configData.encodingAESKey,
                minisignup: this.configData.minisignup,
                yt_minisignup: this.configData.yt_minisignup,
                yt_minisignup_agent: this.configData.yt_minisignup_agent,
                secret: this.configData.secret
              }
            )
            .then((res) => {
              if (res.code == 1) {
                this.$message({
                  type: "success",
                  message: "保存成功",
                });
              }
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleClose(close) {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.resetForm("configData"); //清空表单
          close();
        })
        .catch((_) => {});
    },
    getJsTokenAdnAES() {
      //生成token和AESKey
      if (this.configData.token || this.configData.encodingAESKey) {
        this.$confirm("检测到Token已填写，是否重新生成？", "确认信息", {
          distinguishCancelAndClose: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.getJsToken();
            this.getJsAES();
            this.$message({
              type: "success",
              message: "生成成功",
            });
          })
          .catch((action) => {});
      } else {
        this.getJsToken();
        this.getJsAES();
        this.$message({
          type: "success",
          message: "生成成功",
        });
      }
    },
    getJsToken() {
      //随机生成6-32位token
      var max = 32;
      var min = 6;
      var length = Math.floor(Math.random() * (max - min + 1)) + min;
      var token = this.randomStr(length);
      this.configData.token = token;
    },
    getJsAES() {
      //随机生成43位AESKey
      var encodingAESKey = this.randomStr(43);
      this.configData.encodingAESKey = encodingAESKey;
    },
    randomStr(length) {
      var str =
        "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
      var result = "";
      for (var i = length; i > 0; --i) {
        result += str[Math.floor(Math.random() * str.length)];
      }
      return result;
    },
    copyStr(element) {
      //复制事件
      var clipboard = new Clipboard("." + element);
      clipboard.on("success", (e) => {
        this.$message.success("复制成功");
        // 释放内存
        clipboard.destroy();
      });
      clipboard.on("error", (e) => {
        if (!e.text) {
          return this.$message.error("复制内容不能为空")
        }
        // 不支持复制
        this.$message.warning("该浏览器不支持自动复制");
        // 释放内存
        clipboard.destroy();
      });
    },
  },
  created() {
  },
  mounted() {
    // const clipboard = new Clipboard('.btnCopy');
    // clipboard.on('success', e => {
    //   this.$message.success(e.text + ' 已复制到剪贴板！');
    // });
  },
};
</script>
<style lang="scss">
.enterprise-dialog-box {
    margin: 5vh auto!important;
    .el-dialog__body {
      max-height: calc(90vh - 55px);
      overflow-y: auto;
    }
}
</style>
<style lang="scss" scoped>
.el-divider__text {
  font-weight: 600;
}
.w88 {
  width: 88%;
}
.btnCopy {
  float: right;
}
.btnSave {
  float: right;
  width: 88px;
}
</style>